<template>
  <div>
    <el-upload
      list-type="picture-card"
      :on-preview="preview"
      :limit="1"
      action
      :before-upload="beforeUpload"
      :on-change="changeFile"
      :on-remove="removefileList"
      :file-list="fileList"
      :http-request="upload"
      :class="{ disabled: fileComputed }"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress
      v-if="showPercent"
      :percentage="percent"
      style="width: 180px"
    />
    <el-dialog :visible.sync="showDialog" title="图片预览">
      <img :src="imgUrl" alt="" width="100%" />
    </el-dialog>
  </div>
</template>

<script>
import COS from "cos-js-sdk-v5"; // 引入腾讯云的包
const cos = new COS({
  SecretId: "AKID87rMciZBXeW9WfaFfpoZ8VhiYCey62mM",
  SecretKey: "TlpeDXcR2NSHrCH7i4C5lCNIxNXS7Xid",
}); // 实例化的包 已经具有了上传的能力 可以上传到该账号里面的存储桶了
export default {
  data() {
    return {
      fileList: [],
      showDialog: false,
      imgUrl: "",
      currentID: null, //上传文件前获取当前ID,用来对比上传后替换地址
      percent: 0, //进度
      showPercent: false,
    };
  },
  computed: {
    //如果为true 不显示添加图片+号
    fileComputed() {
      return this.fileList.length === 1;
    },
  },
  methods: {
    //点击预览

    preview(file) {
      console.log(file);
      this.showDialog = true;
      this.imgUrl = file.url;
    },
    //删除fileList文件
    removefileList(file, fileList) {
      //排除要删除图片,删除指定图片
      this.fileList = this.fileList.filter((item) => item.uid !== file.uid);
    },
    changeFile(file, fileList) {
      //   console.log(file);
      //   console.log(fileList);
      this.fileList = fileList.map((item) => item);
    },
    //上传前认证
    beforeUpload(file) {
      //   console.log(file);
      const imgType = [
        "image/webp",
        "image/jpeg",
        "image/gif",
        "image/bmp",
        "image/png",
      ];
      //判断图片格式
      const isImg = imgType.some((item) => item === file.type);
      //图片大小
      const is5M = file.size / 1024 / 1024 < 5;
      if (!isImg) {
        this.$message.error("上传头像图片格式是 JPG,GIF,BMP,PNG,WEBP 格式!");
        return false;
      }
      if (!is5M) {
        this.$message.error("上传图片大于5M");
        return false;
      }
      this.currentID = file.uid;
      this.showPercent = true;
      return isImg && is5M;
    },
    upload(params) {
      if (params.file) {
        cos.putObject(
          {
            Bucket: "lianxi-1312784552" /* 填入您自己的存储桶，必须字段 */,
            Region:
              "ap-guangzhou" /* 存储桶所在地域，例如ap-beijing，必须字段 */,
            Key: "params.file.name" /* 文件名作为key */,
            StorageClass: "STANDARD",
            Body: params.file, // 上传文件对象

            onProgress: (progressData) => {
              //   console.log(JSON.stringify(progressData));
              //   console.log(progressData);
              this.percent = progressData.percent * 100;
            },
          },
          (err, data) => {
            if (!err && data.statusCode == 200) {
              this.fileList = this.fileList.map((item) => {
                if (item.uid === this.currentID) {
                  return { url: "http://" + data.Location, upload: "true " }; // 将本地的地址换成腾讯云地址
                }
                return item;
              });
              setTimeout(() => {
                this.showPercent = false; // 隐藏进度条
                this.percent = 0; // 进度归0
              }, 2000);
            }
          }
        );
      }
    },
  },
};
</script>

<style scoped>
::v-deep.disabled .el-upload--picture-card {
  display: none;
}
</style>